from comman import activator
from comman.functions import *


class VariableLayer(object):  # 定义一个父类
    def update_variable(self, optimizer):
        pass


class Dense(VariableLayer):
    def __init__(self, number_of_neurons, activation, std_initialization=0.01):
        self.number_of_neurons = number_of_neurons
        self.std_initialization = std_initialization

        if isinstance(activation, str):
            self.activation = activator.activator_dict[activation]()
        else:
            self.activation = activation

        # 记录输入x的形状
        self.original_x_shape = None
        self.w = None
        self.b = None
        self.x = None

        self.dw = None
        self.db = None

    def forward(self, x):
        if self.w is None:
            self.w = np.random.randn(x.shape[1], self.number_of_neurons) * self.std_initialization
            self.b = np.random.randn(self.number_of_neurons) * self.std_initialization
            self.original_x_shape = x.shape

        # x 默认已经打平
        self.x = x
        out = np.dot(x, self.w) + self.b

        if self.activation is None:
            return out

        return self.activation.forward(out)

    def backward(self, dout):
        if self.activation is not None:
            dout = self.activation.backward(dout)

        dx = np.dot(dout, self.w.T)
        self.dw = np.dot(self.x.T, dout)
        self.db = np.sum(dout, axis=0)

        self.w -= 0.01 * self.dw
        self.b -= 0.01 * self.db
        return dx

    def update_variable(self, optimizer):
        optimizer.update(zip([self.w, self.b], [self.dw, self.db]))


class Dropout:
    """
    http://arxiv.org/abs/1207.0580
    """

    def __init__(self, dropout_ratio=0.5):
        self.dropout_ratio = dropout_ratio
        self.mask = None

    def forward(self, x, train_flg=True):
        if train_flg:
            self.mask = np.random.rand(*x.shape) > self.dropout_ratio
            return x * self.mask
        else:
            return x * (1.0 - self.dropout_ratio)

    def backward(self, dout):
        return dout * self.mask


class BatchNormalization(VariableLayer):
    """
    http://arxiv.org/abs/1502.03167
    """

    def __init__(self, momentum=0.9, running_mean=None, running_var=None):
        self.gamma = None
        self.beta = None
        self.momentum = momentum
        self.input_shape = None  # Conv层的情况下为4维，全连接层的情况下为2维

        # 测试时使用的平均值和方差
        self.running_mean = running_mean
        self.running_var = running_var

        # backward时使用的中间数据
        self.batch_size = None
        self.xc = None
        self.std = None
        self.dgamma = None
        self.dbeta = None

    def forward(self, x, train_flg=True):
        self.input_shape = x.shape
        if x.ndim != 2:
            N, C, H, W = x.shape
            x = x.reshape(N, -1)

        out = self.__forward(x, train_flg)

        return out.reshape(*self.input_shape)

    def __forward(self, x, train_flg):
        if self.running_mean is None:
            N, D = x.shape
            self.running_mean = np.zeros(D)
            self.running_var = np.zeros(D)

            self.gamma = np.ones(D)
            self.beta = np.zeros(D)

        if train_flg:
            mu = x.mean(axis=0)
            xc = x - mu
            var = np.mean(xc ** 2, axis=0)
            std = np.sqrt(var + 10e-7)
            xn = xc / std

            self.batch_size = x.shape[0]
            self.xc = xc
            self.xn = xn
            self.std = std
            self.running_mean = self.momentum * self.running_mean + (1 - self.momentum) * mu
            self.running_var = self.momentum * self.running_var + (1 - self.momentum) * var
        else:
            xc = x - self.running_mean
            xn = xc / ((np.sqrt(self.running_var + 10e-7)))

        out = self.gamma * xn + self.beta
        return out

    def backward(self, dout):
        if dout.ndim != 2:
            N, C, H, W = dout.shape
            dout = dout.reshape(N, -1)

        dx = self.__backward(dout)

        dx = dx.reshape(*self.input_shape)
        return dx

    def __backward(self, dout):
        dbeta = dout.sum(axis=0)
        dgamma = np.sum(self.xn * dout, axis=0)
        dxn = self.gamma * dout
        dxc = dxn / self.std
        dstd = -np.sum((dxn * self.xc) / (self.std * self.std), axis=0)
        dvar = 0.5 * dstd / self.std
        dxc += (2.0 / self.batch_size) * self.xc * dvar
        dmu = np.sum(dxc, axis=0)
        dx = dxc - dmu / self.batch_size

        self.dgamma = dgamma
        self.dbeta = dbeta

        return dx

    def update_variable(self, optimizer):
        optimizer.update(zip([self.gamma, self.beta]
                             , [self.dgamma, self.dbeta]))


class Conv2D(VariableLayer):
    def __init__(self, filters, kernel_size, strides=(1, 1), padding=0, activation=None, std_initialization=0.01):
        self.filters = filters
        self.kernel_size = kernel_size
        self.std_initialization = std_initialization

        self.strides = strides
        self.padding = padding

        # 激活函数
        if isinstance(activation, str):
            self.activation = activator.activator_dict[activation]()
        else:
            self.activation = activation

        # forward
        self.w = None
        self.b = None

        # 中间数据（backward时使用）
        self.x = None
        self.col = None
        self.col_w = None

        # 权重和偏置参数的梯度
        self.dw = None
        self.db = None

    def forward(self, x):
        N, C, H, W = x.shape
        if self.w is None:
            if isinstance(self.kernel_size, int):
                self.w = np.random.randn(self.filters, C, self.kernel_size, self.kernel_size) * self.std_initialization
            else:
                self.w = np.random.randn(self.filters, C, *self.kernel_size) * self.std_initialization
            self.b = np.zeros(self.filters)

        # FC == C
        FN, FC, FH, FW = self.w.shape

        out_h = 1 + int((H + 2 * self.padding - FH) / self.strides[0])
        out_w = 1 + int((W + 2 * self.padding - FW) / self.strides[1])

        # 把输入图片进行打平
        col = im2col(x, FH, FW, self.strides, self.padding)
        # 将权重(核、过滤器)进行打平
        col_w = self.w.reshape(FN, -1).T

        out = np.dot(col, col_w) + self.b
        out = out.reshape(N, out_h, out_w, -1).transpose(0, 3, 1, 2)

        self.x = x
        self.col = col
        self.col_w = col_w

        return self.activation.forward(out)

    def backward(self, dout):
        FN, C, FH, FW = self.w.shape

        dout = self.activation.backward(dout)
        dout = dout.transpose(0, 2, 3, 1).reshape(-1, FN)

        self.db = np.sum(dout, axis=0)
        self.dw = np.dot(self.col.T, dout)
        self.dw = self.dw.transpose(1, 0).reshape((FN, C, FH, FW))

        dcol = np.dot(dout, self.col_w.T)
        dx = col2im(dcol, self.x.shape, FH, FW, self.strides, self.padding)

        return dx

    def update_variable(self, optimizer):
        optimizer.update(zip([self.w, self.b], [self.dw, self.db]))


class Pooling:
    def __init__(self, pool_h, pool_w, stride=1, pad=0):
        self.pool_h = pool_h
        self.pool_w = pool_w
        self.stride = stride

        self.pad = pad

        self.x = None
        self.arg_max = None

    def forward(self, x):
        N, C, H, W = x.shape
        out_h = int(1 + (H - self.pool_h) / self.stride)
        out_w = int(1 + (W - self.pool_w) / self.stride)

        col = im2col(x, self.pool_h, self.pool_w, (self.stride, self.stride), self.pad)
        col = col.reshape(-1, self.pool_h * self.pool_w)

        arg_max = np.argmax(col, axis=1)
        out = np.max(col, axis=1)
        out = out.reshape((N, out_h, out_w, C)).transpose(0, 3, 1, 2)

        self.x = x
        self.arg_max = arg_max

        return out

    def backward(self, dout):
        dout = dout.transpose(0, 2, 3, 1)

        pool_size = self.pool_h * self.pool_w
        dmax = np.zeros((dout.size, pool_size))
        dmax[np.arange(self.arg_max.size), self.arg_max.flatten()] = dout.flatten()
        dmax = dmax.reshape(dout.shape + (pool_size,))

        dcol = dmax.reshape(dmax.shape[0] * dmax.shape[1] * dmax.shape[2], -1)
        dx = col2im(dcol, self.x.shape, self.pool_h, self.pool_w, (self.stride, self.stride), self.pad)

        return dx


class Flatten:
    def __init__(self):
        self.original_x_shape = None

    def forward(self, x):
        self.original_x_shape = x.shape
        x = x.reshape(x.shape[0], -1)
        return x

    def backward(self, dout):
        dx = dout.reshape(self.original_x_shape)
        return dx


class Reshape:
    def __init__(self, target_x_shape):
        self.target_x_shape = target_x_shape
        self.original_x_shape = None

    def forward(self, x):
        self.original_x_shape = x.shape
        x = x.reshape(x.shape[0], *self.target_x_shape)
        return x

    def backward(self, dout):
        dx = dout.reshape(self.original_x_shape)
        return dx
